package indi.wshape1.takeawaydeliveryinfo.service.impl;

import indi.wshape1.takeawaydeliveryinfo.dao.BlockDAO;
import indi.wshape1.takeawaydeliveryinfo.dao.impl.BlockDAOImpl;
import indi.wshape1.takeawaydeliveryinfo.domain.Block;
import indi.wshape1.takeawaydeliveryinfo.domain.Group;
import indi.wshape1.takeawaydeliveryinfo.service.BlockService;
import indi.wshape1.takeawaydeliveryinfo.service.GroupService;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Wshape1
 * @create 2022-11-12 10:31
 */

public class BlockServiceImpl implements BlockService {

    private final BlockDAO blockDAO = new BlockDAOImpl();


    @Override
    public Block getByName(String name) {
        return blockDAO.getByName(name);
    }

    @Override
    public boolean add(Block block) {
        if (getByName(block.getName()) == null) {
            blockDAO.add(block);
            return true;
        }
        return false;
    }

    @Override
    public boolean delByName(String name) throws SQLException {
        // do more
        if (getByName(name) != null && !"null".equals(name)) {
            // del takeout_info s
            GroupService groupService = new GroupServiceImpl();
            List<Group> listByBlock = groupService.getListByBlock(name);
            for (Group g : listByBlock) {
                groupService.delByName(g.getName());
            }
            blockDAO.delByName(name);
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Block block, String oldName) throws SQLException {
        if (getByName(block.getName()) != null) {
            if (oldName.equals(block.getName()) || getByName(block.getName()) == null) {
                blockDAO.update(block, oldName);
                return true;
            }
        }
        return false;
    }

    @Override
    public List<Block> getList() {
        return blockDAO.getList();
    }

    @Override
    public List<Block> getListByPage(int page) {
        return blockDAO.getListByPage(page);
    }

    @Override
    public List<Block> getListByKeywordAndPage(String keyword, int page) {
        return blockDAO.getListByKeywordAndPage(keyword, page);
    }

    @Override
    public List<Block> getListByKeyword(String keyword) {
        return blockDAO.getListByKeyword(keyword);
    }

    @Override
    public int getCount() {
        return blockDAO.getCount();
    }

    @Override
    public int getCountByKeyword(String keyword) {
        return blockDAO.getCountByKeyword(keyword);
    }

    @Override
    public int getPageCount() {
        return (getCount() - 1 + blockDAO.getCountPerPage()) / blockDAO.getCountPerPage();
    }

    @Override
    public int getPageCountByKeyword(String keyword) {
        return (getCountByKeyword(keyword) - 1 + blockDAO.getCountPerPage()) / blockDAO.getCountPerPage();
    }

}
